

<template>
  <PlusDialogForm
      class="teacher-form"
      ref="plusFormInstance"
      v-model:visible="dialogShow"
      v-model="formData"
      :form="{group:columns,  cardProps:{ shadow:'never' }, colProps:{ span:6 }, labelWidth:'100px',  labelPosition:'right',  rules:formRules }"
      :dialog="{ title: dialogTitle, width: '1200px', top: '12vh', confirmLoading }"
      @confirm="handleSubmit"
      @cancel="handleCancel"
  >
    <template #plus-field-emergency>
      <div class="flex justify-end  w-full pb5">
        <el-button size="small" type="primary" @click="addEmergency">添加</el-button>
      </div>
      <el-table :data="formData.emergency">
        <el-table-column align="center" label="联系人姓名">
          <template #default="{row,$index}">
            <el-form-item label="" :prop="`emergency[${$index}].contactName`">
              <el-input placeholder="请输入" v-model="row.contactName"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" label="关系">
          <template #default="{row,$index}">
            <el-form-item label="" :prop="`emergency[${$index}].contactRelation`">
              <el-select v-model="row.contactRelation">
                <el-option v-for="item in edu_emergency_relation" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" label="联系方式">
          <template #default="{row,$index}">
            <el-form-item label="" :prop="`emergency[${$index}].contactPhone`">
              <el-input placeholder="请输入" v-model="row.contactPhone"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{row,$index}">
            <el-button type="danger" link @click="formData.emergency.splice($index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template #plus-field-experience>
      <div class="flex justify-end  w-full pb5">
        <el-button size="small" type="primary" @click="addExperience">添加</el-button>
      </div>
      <el-table :data="formData.experience">
        <el-table-column align="center" label="学校名称">
          <template #default="{row,$index}">
            <el-form-item label="" :prop="`emergency[${$index}].schoolName`">
              <el-input placeholder="请输入" v-model="row.schoolName"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" label="时间范围">
          <template #default="{row,$index}">
            <el-form-item label="" :prop="`emergency[${$index}].timeRange`">
              <el-date-picker v-model="row.timeRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" label="专业信息">
          <template #default="{row,$index}">
            <el-form-item label="" :prop="`emergency[${$index}].major`">
              <el-input v-model="row.major" placeholder="请输入专业信息"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注">
          <template #default="{row,$index}">
            <el-form-item label="" :prop="`emergency[${$index}].remark`">
              <el-input v-model="row.remark" placeholder="请输入专业信息"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{row,$index}">
            <el-button type="danger" link @click="formData.experience.splice($index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template #plus-field-deptId>
      <el-tree-select v-model="formData.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属部门" check-strictly />
    </template>
  </PlusDialogForm>
</template>


<script setup>
import { getTeacherApi, addTeacherApi, updateTeacherApi } from "@/api/edutation/teacher";
import { getCurrentInstance,ref } from "vue"
import {deptTreeSelect, getUser} from "@/api/system/user.js";
import {useCommonData} from "@/hooks/useCommonData.js";
const { proxy } = getCurrentInstance();
const { sys_user_sex ,edu_emergency_relation,edu_teacher_state,edu_teacher_level,edu_degree_data
} = proxy.useDict('edu_degree_data','edu_teacher_level','edu_teacher_state','sys_user_sex','edu_student_state','edu_emergency_relation');

const primaryKey = "id"  // 主键
const emit = defineEmits(["update"]);
const {  schoolDataList, getSchoolDataList } = useCommonData();

const dialogShow = ref(false);
const confirmLoading = ref(false)
const isEdit = computed(() =>!!formData.value[primaryKey])
const dialogTitle = computed(() => (isEdit.value ? '编辑' : '新增')+'教师')
const plusFormInstance = ref(null);
const formInstance = computed(()=>plusFormInstance.value?.formInstance)
const postOptions = ref([])
const roleOptions = ref([])
const deptOptions = ref([])
deptTreeSelect().then((response) => {
  deptOptions.value = response.data
})
getUser().then(({data}) => {
  postOptions.value = data.posts
  roleOptions.value = data.roles
})
getSchoolDataList();

const columns = computed(()=>[
  {
    title:"账号信息",
    columns:[
      {
        label: '账户名称',
        prop: 'userName',
        fieldProps:{
          modelModifiers: { trim: true },
        },
      },
      {
        label: '账户密码',
        prop: 'password',
        hideInForm: isEdit.value,
        fieldProps:{
          showPassword:true,
          type:'password',
          modelModifiers: { trim: true },
        },
      },
      {
        label: '所属部门',
        prop: 'deptId',
        valueType: 'tree-select',
        options:deptOptions.value,
        fieldProps:{
          props:{ value: 'id', label: 'label', children: 'children' },
          valueKey:'id',
          checkStrictly: true,
        },
      },
      {
        label: '岗位',
        prop: 'postIds',
        valueType: 'select',
        options:postOptions.value,
        optionsMap:{
          label:'postName',
          value:'postId'
        },
        fieldProps:{
          multiple: true,
        },
      },
      {
        label: '角色',
        prop: 'roleIds',
        options: roleOptions.value,
        valueType: 'select',
        optionsMap:{
          label:'roleName',
          value:'roleId'
        },
        fieldProps:{
          multiple: true,
        },
      },
      {
        label: '手机号码',
        prop: 'phonenumber',
        fieldProps:{
          modelModifiers: { trim: true },
          maxLength:11
        },
      },
      {
        label: '邮箱',
        prop: 'email',
        fieldProps:{
          modelModifiers: { trim: true },
          maxLength:11
        },
      },
      {
        label: '性别',
        prop: 'sex',
        valueType: 'select',
        options: sys_user_sex.value,
        fieldProps:{
        },
      },

    ],
  },
  {
    title:"基本信息",
    columns:[
      {
        label: '教师名称',
        prop: 'nickName',
        valueType:'input',
        fieldProps:{
          maxlength: 200,
          modelModifiers: { trim: true },
        },
      },
      {
        label: '身份证号码',
        prop: 'idCard',
        valueType:'input',
        fieldProps:{
          maxlength: 200,
          modelModifiers: { trim: true },
        },
      },
      {
        label: '出生日期',
        prop: 'birthday',
        valueType:'input',
        fieldProps:{
          maxlength: 200,
          modelModifiers: { trim: true },
        },

      },
      {
        label: '教师职称',
        prop: 'teacherLevel',
        valueType:'select',
        options:edu_teacher_level.value,
        optionsMap:{},

      },
      {
        label: '最高学历',
        prop: 'degree',
        valueType:'select',
        options:edu_degree_data.value,
        optionsMap:{},

      },
      {
        label: '归属学校',
        prop: 'schoolId',
        valueType:'select',
        options:schoolDataList.value,
        optionsMap:{
          label:'schoolName',
          value:'schoolId',
        },
      },
      {
        label: '老师状态',
        prop: 'state',
        valueType:'select',
        options:edu_teacher_state.value,
        optionsMap:{},

      },
      {
        label: '户籍地址',
        prop: 'cardAddress',
        valueType:'textarea',
        colProps:{
          span:12
        },
        fieldProps:{
          maxlength: 200,
          showWordLimit: true,
          modelModifiers: { trim: true },
          autosize: { minRows: 2, maxRows: 4 }
        },

      },{
        label: '家庭地址',
        prop: 'houseAddress',
        valueType:'textarea',
        colProps:{
          span:12
        },
        fieldProps:{
          maxlength: 200,
          showWordLimit: true,
          modelModifiers: { trim: true },
          autosize: { minRows: 2, maxRows: 4 }
        },

      },

    ],
  },
  {
    title:"教育经历",
    columns:[
      {
        label: '教育经历',
        prop: 'experience',
        valueType:'input',
        colProps:{
          span:24
        },
        fieldProps:{
          maxlength: 200,
          modelModifiers: { trim: true },
        },

      },

    ],
  },
  {
    title:"紧急联系人",
    columns:[
      {
        label: '紧急联系',
        prop: 'emergency',
        valueType:'textarea',
        colProps:{
          span:24
        },
        fieldProps:{
          maxlength: 200,
          showWordLimit: true,
          modelModifiers: { trim: true },
          autosize: { minRows: 2, maxRows: 4 }
        },

      },
    ],
  },
  {
    title:"紧急联系人",
    columns:[
      {
        label: '备注',
        prop: 'remark',
        valueType:'textarea',
        colProps:{
          span:24
        },
        fieldProps:{
          maxlength: 200,
          showWordLimit: true,
          modelModifiers: { trim: true },
          autosize: { minRows: 2, maxRows: 4 }
        },

      },
    ],
  },

  ])

const formData = ref({
  teacherName: "",
  idCard: "",
  teacherNumber: "",
  phone: "",
  state: "",
  birthday: "",
  cardAddress: "",
  houseAddress: "",
  emergency: [],
  teacherId: "",
  schoolId: "",
  campusId: "",
  teacherLevel: "",
  degree: "",
  experience: [],
  remark: "",

});
const formRules = ref({
  teacherName: [{ required: true, message: "教师名称不能为空", trigger: ["blur"] }],
  idCard: [{ required: true, message: "身份证号码不能为空", trigger: ["blur"] }],
  teacherNumber: [{ required: true, message: "教师编号不能为空", trigger: ["blur"] }],
  state: [{ required: true, message: "老师状态不能为空", trigger: ["blur","change"] }],
  birthday: [{ required: true, message: "出生日期不能为空", trigger: ["blur"] }],
  houseAddress: [{ required: true, message: "家庭地址不能为空", trigger: ["blur"] }],
  schoolId: [{ required: true, message: "归属学校不能为空", trigger: ["blur","change"] }],
  campusId: [{ required: true, message: "归属校区不能为空", trigger: ["blur","change"] }],
  teacherLevel: [{ required: true, message: "教师职称不能为空", trigger: ["blur","change"] }],
  degree: [{ required: true, message: "最高学历不能为空", trigger: ["blur","change"] }],
  userName: [
    { required: true, message: '用户账号不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '用户密码不能为空', trigger: 'blur' },
    { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
  ],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
  phonenumber: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }]
});

// 添加紧急联系人
const addEmergency = ()=>{
  formData.value.emergency.push({
    contactName:'',
    contactPhone:'',
    contactRelation:'',
  })
}
// 添加教育经历
const addExperience = ()=>{
  formData.value.experience.push({
    schoolName:'',
    major:'',
    remark:'',
    timeRange:[],
  })
}

// 确定按钮操作
const handleSubmit = async () => {
  try {
    confirmLoading.value = true

    // 整理数据
    const { emergency, experience, ...data } = formData.value
    data.emergency = JSON.stringify(emergency)
    data.experience = JSON.stringify(experience)
    if (isEdit.value) {
      await updateTeacherApi(data)
      proxy.$modal.msgSuccess("修改成功")
    } else {
      await addTeacherApi(data)
      proxy.$modal.msgSuccess("新增成功")
    }
    handleCancel();
    emit('update')
  } catch (error) {
    console.warn('提交错误:', error)
  } finally {
    confirmLoading.value = false
  }
}

// 取消按钮操作
function handleCancel() {
  dialogShow.value = false
  onReset();
}

// 重置数据
const onReset = () => {
  formData.value = {
    teacherName: "",
    idCard: "",
    teacherNumber: "",
    phone: "",
    state: "",
    birthday: "",
    cardAddress: "",
    houseAddress: "",
    emergency: [],
    teacherId: "",
    schoolId: "",
    campusId: "",
    teacherLevel: "",
    degree: "",
    experience: [],
    remark: "",

  }
  formInstance.value.resetFields();
}
// 查询回显
const getDetail = async (key) => {
  const { data } = await  getTeacherApi(key)
  try {
    data.experience = JSON.parse(data.experience)
  } catch (e){
    data.experience = []
  }
  try {
    data.emergency = JSON.parse(data.emergency)
  } catch (e){
    data.emergency = []
  }
  formData.value = data;
}
// 打开弹框
const openDialog = async (row) => {
  if(row && row[primaryKey]){
    await getDetail(row[primaryKey])
  }
  dialogShow.value = true;
};
defineExpose({ openDialog });
</script>
<style lang="scss" scoped>


</style>

